/**
 * 
 */
package com.amkai.aes.webservice.binary.objecthandler.billing;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.amkai.aes.aescommon.service.binary.job.billing.DeleteBatchJob;
import com.amkai.aes.aescommon.service.result.billing.DeleteBatchResult;
import com.amkai.aes.generatedbeans.billinginterval.Batch;
import com.amkai.aes.generatedbeans.billinginterval.Expected;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.extensions.server.services.ServerServiceManager;
import com.amkai.rad.designerbase.beans.ChangedKind;

/**
 * @author Cseki
 *
 */
// KKORNEL: AES-11685 - return value is canged to DeleteBatchResult from Boolean
public class DeleteBatchHandler implements JobObjectHandler<DeleteBatchJob, Serializable, DeleteBatchResult> {
	private static final Log logger = LogFactory.getLog(DeleteBatchHandler.class);
	/* (non-Javadoc)
	 * @see com.amkai.aes.webservice.binary.JobObjectHandler#process(com.amkai.aes.aescommon.service.binary.job.Job, java.io.Serializable)
	 */
	public DeleteBatchResult process(DeleteBatchJob job, Serializable object) throws Exception {
		String batchQuery = "Select bat FROM Batch AS bat \n" +
							"WHERE bat.id = :batid";
		
		DeleteBatchResult result = new DeleteBatchResult();
		if (object != null && object instanceof Batch) {
			Batch b = (Batch) object;
			SessionManager sm = SiteManager.Start();
			try {
				sm.openSession();
				sm.openTransaction();
				// AES-15935
				ServerServiceManager.getInstance().getVersionManager().checkValidity(b);
				Batch bb = (Batch) sm.execute(batchQuery).setLong("batid", b.getId().longValue()).uniqueResult();
				result.setErrorMessage(getErrorMessage(bb));
				if (result.getErrorMessage() == null){
					result.setDeletable(true);
					bb.setChangedKind(ChangedKind.DELETED);
					for (Expected exp : bb.getExpecteds()){
						exp.setChangedKind(ChangedKind.DELETED);
						sm.saveRAD(exp);
					}
					// batch list of period is changed - perform a version change in period
					ServerServiceManager.getInstance().getVersionManager().update(bb.getPeriod());
					sm.saveRAD(bb);
				}
				sm.commitTransaction();
			} catch (Exception e) {
				logger.error("DeleteBatchHandler: ", e);
				sm.rollbackTransaction();
				result.setDeletable(false);
				result.setErrorMessage("Exception occured during deleting batch!");
				throw e;
			} finally{
				sm.closeSession();
			}
		}
		return result;
	}
	
	private String getErrorMessage(Batch batch){
		if (batch.getClosed() != null){
			return "Batch '"+batch.getDescription()+"' can not be deleted, because it is closed!";
		} if (batch.getEntries() != null && !batch.getEntries().isEmpty()){
			return "Batch '"+batch.getDescription()+"' can not be deleted, because it has associated transactions!";
		}
		return null;
	}
	
}
